package middleware

import (
	"awesomeProject/app/model"
	"awesomeProject/app/response"
	"awesomeProject/util"
	"github.com/gin-gonic/gin"
	"net/http"
)

func ShopAuth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		user, _ := ctx.Get("user")
		userObj := user.(model.User)
		//global.LoggerOut(userObj.CompanyId)
		if userObj.CompanyId == 0 {
			//global.LoggerOut(userObj.ShopIds)
			//_, companyShops := shopSrv.QueryShopIdsByUser(userObj)
			_, companyShops := shopSrv.QueryShopIdsByUserFull(userObj)
			if userObj.SuperAdmin {
				//userObj.ShopIds = userObj.ShopIds
				userObj.ShopIds = companyShops
			} else {
				userObj.ShopIds = util.IntersectUIntArray(userObj.ShopIds, companyShops)
			}
			//global.LoggerOut(userObj.ShopIds)
			ctx.Set("user", userObj)
			ctx.Next()
			return
		}
		// 重新整理用户店铺ID
		var actualShopIds []uint
		//_, companyShops := shopSrv.QueryShopIdsByUser(userObj)
		_, companyShops := shopSrv.QueryShopIdsByUserFull(userObj)
		for _, cs := range companyShops {
			for _, sid := range userObj.ShopIds {
				if sid == cs {
					actualShopIds = append(actualShopIds, sid)
				}
			}
		}
		//global.LoggerOut(actualShopIds)
		userObj.ShopIds = actualShopIds

		// 判断是否分配店铺权限
		if len(userObj.ShopIds) == 0 {
			ctx.AbortWithStatusJSON(http.StatusForbidden, response.ErrForbidden.SetMsg("当前登录用户未分配店铺权限，请联系管理员解决"))
			return
		}

		ctx.Set("user", userObj)
		ctx.Next()
	}
}
